// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'paginated_data_table_ext.dart';
import 'package:flutter_search_bar/flutter_search_bar.dart';
class Dessert {
  Dessert(this.name,this.value);
  final String name;
  final String value;
  bool selected = false;
}

class DessertDataSource extends DataTableSource {
  final List<Dessert> _desserts = <Dessert>[
    new Dessert('Frozen yogurt','1'),
    new Dessert('Ice cream sandwich','1'),
    new Dessert('Eclair','1'),
    new Dessert('Cupcake','1'),
    new Dessert('Gingerbread','1'),
    new Dessert('Jelly bean','1'),
    new Dessert('Lollipop','1'),
    new Dessert('Honeycomb','1'),
    new Dessert('Donut','1'),
    new Dessert('KitKat','1'),

    new Dessert('Frozen yogurt with sugar','1'),
    new Dessert('Ice cream sandwich with sugar','1'),
    new Dessert('Eclair with sugar','1'),
    new Dessert('Cupcake with sugar','1'),
    new Dessert('Gingerbread with sugar','1'),
    new Dessert('Jelly bean with sugar','1'),
    new Dessert('Lollipop with sugar','1'),
    new Dessert('Honeycomb with sugar','1'),
    new Dessert('Donut with sugar','1'),
    new Dessert('KitKat with sugar','1'),
  ];

  void _sort<T>(Comparable<T> getField(Dessert d), bool ascending) {
    _desserts.sort((Dessert a, Dessert b) {
      if (!ascending) {
        final Dessert c = a;
        a = b;
        b = c;
      }
      final Comparable<T> aValue = getField(a);
      final Comparable<T> bValue = getField(b);
      return Comparable.compare(aValue, bValue);
    });
    notifyListeners();
  }

  int _selectedCount = 0;

  @override
  DataRow getRow(int index) {
    assert(index >= 0);
    if (index >= _desserts.length)
      return null;
    final Dessert dessert = _desserts[index];
    return new DataRow.byIndex(
        index: index,
        selected: dessert.selected,
        onSelectChanged: (bool value) {
          if (dessert.selected != value) {
            _selectedCount += value ? 1 : -1;
            assert(_selectedCount >= 0);
            dessert.selected = value;
            notifyListeners();
          }
        },
        cells: <DataCell>[
          new DataCell (
            new Text('${dessert.name}'),

          )
        ]
    );
  }

  @override
  int get rowCount => _desserts.length;

  @override
  bool get isRowCountApproximate => false;

  @override
  int get selectedRowCount => _selectedCount;

  void _selectAll(bool checked) {
    for (Dessert dessert in _desserts)
      dessert.selected = checked;
    _selectedCount = checked ? _desserts.length : 0;
    notifyListeners();
  }
  List getSelected(){
    List list = _desserts
                .where((Dessert ent) => ent.selected==true)
                .map((Dessert ent) =>ent.name )
                .toList();
    return list;
  }
}

class DataTableDemo extends StatefulWidget {
  final List<dynamic> selected;

  DataTableDemo({Key key, @required this.selected}) : super(key: key);
//  final InitList initList;
  @override
  State<StatefulWidget> createState(){
    print(selected);
    _DataTableDemoState view=new _DataTableDemoState();

    return view;
  }
}

class _DataTableDemoState extends State<DataTableDemo> {
  int _rowsPerPage = PaginatedDataTable.defaultRowsPerPage;
  int _sortColumnIndex;
  SearchBar searchBar;
  bool _sortAscending = true;
  final DessertDataSource _dessertsDataSource = new DessertDataSource();
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  @override
  void initState() {
    super.initState();
    _refreshData();
  }

_refreshData() {
    final Completer<Null> completer = new Completer<Null>();
    print(widget.selected);
    if(widget.selected!=null){
      if(widget.selected.isNotEmpty){
        _dessertsDataSource._desserts.forEach(
                (ent){
              if(widget.selected.contains(ent.name)){
                ent.selected=true;
              }
            }
        );
        _dessertsDataSource._selectedCount=widget.selected.length;
      }
    }
  }
  AppBar buildAppBar(BuildContext context) {
    return new AppBar(
        title: new Text('My Home Page'),
        actions: [searchBar.getSearchAction(context)]
    );
  }
  void onSubmitted(String value) {
    setState(() => _scaffoldKey.currentState
        .showSnackBar(new SnackBar(content: new Text('You wrote $value!'))));
  }
  _DataTableDemoState() {
    searchBar = new SearchBar(
        inBar: true,
        setState: setState,
        onSubmitted: onSubmitted,
        buildDefaultAppBar: buildAppBar
    );

  }
  void _sort<T>(Comparable<T> getField(Dessert d), int columnIndex, bool ascending) {
    _dessertsDataSource._sort<T>(getField, ascending);
    setState(() {
      _sortColumnIndex = columnIndex;
      _sortAscending = ascending;
    });
  }
  void _handleSubmitted() {
//    print(_dessertsDataSource. getSelected().toString());
    Navigator.pop(context, _dessertsDataSource. getSelected());
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: searchBar.build(context),
        key: _scaffoldKey,
        body: new ListView(
//            padding: const EdgeInsets.all(20.0),
            children: <Widget>[
              new PaginatedDataTableExt(
                  header: const Text('Nutrition'),
                  rowsPerPage: _rowsPerPage,
                  onRowsPerPageChanged: (int value) { setState(() { _rowsPerPage = value; }); },
                  sortColumnIndex: _sortColumnIndex,
                  sortAscending: _sortAscending,
                  onSelectAll: _dessertsDataSource._selectAll,
                  columns: <DataColumn>[
                    new DataColumn(
                        label: const Text('全选'),
                        onSort: (int columnIndex, bool ascending) => _sort<String>((Dessert d) => d.name, columnIndex, ascending)
                    )
                  ],
                  source: _dessertsDataSource
              )
            ]
        ),
      bottomNavigationBar:new RaisedButton(
        child: const Text('确定'),
        onPressed: _handleSubmitted,
      ),
    );
  }
}
